package cn.gengar.domain.trade.service.lock;

import cn.gengar.domain.trade.adapter.repository.ITradeRepository;
import cn.gengar.domain.trade.model.aggregate.GroupBuyOrderAggregate;
import cn.gengar.domain.trade.model.entity.*;
import cn.gengar.domain.trade.model.valobj.GroupBuyProgressVO;
import cn.gengar.domain.trade.service.ITradeLockOrderService;
import cn.gengar.domain.trade.service.lock.factory.TradeSettlementRuleFilterFactory;
import cn.gengar.types.design.framework.link.model2.chain.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class TradeLockOrderService implements ITradeLockOrderService {

    @Resource
    private ITradeRepository repository;

    @Resource
    private BusinessLinkedList<TradeRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeRuleFilterBackEntity> tradeRuleFilter;

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayActivityEntity payActivityEntity, PayDiscountEntity payDiscountEntity) throws Exception {

        TradeRuleFilterBackEntity filterBackEntity = tradeRuleFilter.apply(TradeRuleCommandEntity.builder()
                .activityId(payActivityEntity.getActivityId())
                .userId(userEntity.getUserId())
                .build(), TradeSettlementRuleFilterFactory.DynamicContext.builder().build());

        Integer userTakeOrderCount = filterBackEntity.getUserTakeOrderCount();

        GroupBuyOrderAggregate groupBuyOrderAggregate = GroupBuyOrderAggregate.builder()
                .userEntity(userEntity)
                .payActivityEntity(payActivityEntity)
                .payDiscountEntity(payDiscountEntity)
                .userTakeOrderCount(userTakeOrderCount)
                .build();

        return repository.lockMarketPayOrder(groupBuyOrderAggregate);
    }

    @Override
    public GroupBuyProgressVO queryGroupBuyProgress(String teamId) {
        return repository.queryGroupBuyProgress(teamId);
    }

    @Override
    public MarketPayOrderEntity queryNoPayMarketPayOrderByOutTradeNo(String userId, String outTradeNo) {
        return repository.queryMarkerPayOrderByOutTradeNo(userId, outTradeNo);
    }
}
